package com.xiangshizhineng.tianzhangzhi.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiangshizhineng.tianzhangzhi.app.common.R;
import com.xiangshizhineng.tianzhangzhi.app.common.ResultCode;
import com.xiangshizhineng.tianzhangzhi.app.common.base.BaseController;
import com.xiangshizhineng.tianzhangzhi.app.config.MessageVo;
import com.xiangshizhineng.tianzhangzhi.app.config.Sender;
import com.xiangshizhineng.tianzhangzhi.app.filter.AppToken;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.Task;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.TzMes;
import com.xiangshizhineng.tianzhangzhi.app.model.request.ETRequest;
import com.xiangshizhineng.tianzhangzhi.app.model.request.TaskRequest;
import com.xiangshizhineng.tianzhangzhi.app.model.request.TrajectoryRequest;
import com.xiangshizhineng.tianzhangzhi.app.model.response.*;
import com.xiangshizhineng.tianzhangzhi.app.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.xiangshizhineng.tianzhangzhi.app.utils.CalculateUtil.dateDiff;
import static com.xiangshizhineng.tianzhangzhi.app.utils.ConstantUtils.CB_1;
import static com.xiangshizhineng.tianzhangzhi.app.utils.ConstantUtils.TZJB_2;


@RestController
@RequestMapping("/task")
@Slf4j
@Api(tags = "任务管理")
public class TaskController extends BaseController<Task> {

    @Autowired
    private TaskService taskService;

    @Autowired
    private TrajectoryService trajectoryService;

    @Autowired
    private PatrolService patrolService;

    @Autowired
    private PatrolFileService patrolFileService;

    @Autowired
    private MesService mesService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskHistoryService taskHistoryService;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private EventService eventService;

    @Autowired
    private Sender sender;

    @ApiOperation(value = "任务详情", notes = "任务详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "任务id(两个参数一个有值另一个就要为0)", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "fId", value = "图斑id(两个参数一个有值另一个就要为0)", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/cbDetail")
    @Transactional
    @AppToken
    public R<TPPResponse> cbDetail(Long id, Long fId) {
        TPPResponse tppResponse = new TPPResponse();
        //查看催办任务后新消息提醒减1
        if (id != 0) {
            UpdateWrapper<TzMes> update = new UpdateWrapper<TzMes>();
            update.set("state", "1");
            update.eq("id_by_type", id).eq("type", "5");
            mesService.update(update);
        }
        String taskId = null;
        if (fId != 0) {
            try {
                taskId = taskService.getOne(new QueryWrapper<TaskResponse>().select("id").eq("tb_id", fId)).getId().toString();
            } catch (MyBatisSystemException e) {

                System.out.println("图斑对应了多个任务");
            }
        } else {
            taskId = id.toString();
        }
        if (!StringUtils.isEmpty(taskId)) {
            PatrolResponse patrolResponse = patrolService.getOne(new QueryWrapper<PatrolResponse>().select("s_time", "e_time",
                    "xcsj", "xclc", "xczt", "task_describe", "task_status").eq("task_id", taskId));
            List<PatrolFileResponse> PFileList = patrolFileService.list(new QueryWrapper<PatrolFileResponse>().select("file_path").
                    eq("task_id", taskId));
            List<String> pics = new ArrayList<>();
            for (PatrolFileResponse p : PFileList) {
                pics.add(p.getFilePath());
            }
            tppResponse.setPatrol(patrolResponse);
            tppResponse.setPics(pics);
        }
        TaskResponse taskResponse = taskService.cbTaskDetail(id, fId);
        if (taskResponse == null) {
            TaskResponse taskResponseHis = taskService.cbTaskDetailHis(id,fId);
            tppResponse.setTask(taskResponseHis);
        } else {
            tppResponse.setTask(taskResponse);
        }
        return R.success(tppResponse);
    }

    @ApiOperation(value = "图斑查看任务", notes = "图斑查看任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", paramType = "query"),
            @ApiImplicitParam(name = "fId", value = "图斑id", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/tbTask")
    @Transactional
    @AppToken
    public R<List<TaskResponse>> tbTask(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                                        @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                                        @RequestParam(value = "fId", required = false)Long fId) {
        Page<TaskResponse> taskList = taskService.page(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().
                select("id","task_name","create_time","task_type_id","task_s_time","task_e_time","tb_id","xzqhdm","task_status_id","task_xcr").
                eq("tb_id",fId));
        return R.success(taskList);
    }

    @ApiOperation(value = "任务菜单我的任务", notes = "在期限内我领取的任务,测试userId:1470590000308027393")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前用户的id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskName", value = "输入任务名称查询", dataType = "Long", paramType = "query", required = false),
            @ApiImplicitParam(name = "taskTypeId", value = "任务类型(15定期核查,16下发图斑,17上报事件,0全部类型)", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskStatusId", value = "任务状态(18巡查中,19待巡查,20已巡查，21已逾期，0全部类型)", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "createTime", value = "创建时间排序(true倒序，false正序)", dataType = "boolean", paramType = "query", required = false)
    })
    @GetMapping("/myTask")
    @AppToken
    public R myTask(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                    @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                    @RequestParam(value = "userId", required = false) String userId,
                    @RequestParam(value = "taskName", required = false) String taskName,
                    @RequestParam(value = "taskTypeId", required = false) Long taskTypeId,
                    @RequestParam(value = "taskStatusId", required = false) Long taskStatusId,
                    @RequestParam(value = "createTime", required = false, defaultValue = "true") boolean createTime) {
        IPage<TaskResponse> myTasks = taskService.selectByMyWrapper(new Page<TaskResponse>(p, s), new QueryWrapper<TaskResponse>().
                select("id", "task_name", "task_status_id", "cb", "task_s_time", "task_e_time").
                eq("task_xcr", userId).
                like(StringUtils.isNotEmpty(taskName), "task_name", taskName).
                eq(taskTypeId != 0, "task_type_id", taskTypeId).
                eq(taskStatusId != 0, "task_status_id", taskStatusId).
                orderByAsc(!createTime, "create_time").
                orderByDesc(createTime, "create_time"));
        return R.success(myTasks);
    }

    @ApiOperation(value = "任务菜单全部任务", notes = "期限内的全部任务，包括所有状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前用户的id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskName", value = "输入任务名称查询", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "taskTypeId", value = "任务类型(15定期核查,16下发图斑,17上报事件，0全部类型)", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskStatusId", value = "任务状态(18巡查中,19待巡查,20已巡查，21已逾期，0全部类型)", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "createTime", value = "创建时间排序(true倒序，false正序)", dataType = "boolean", paramType = "query", required = false)
            })
    @GetMapping("/allTask")
    @AppToken
    public R allTask(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                     @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                     @RequestParam(value = "userId", required = false) String userId,
                     @RequestParam(value = "taskName", required = false) String taskName,
                     @RequestParam(value = "taskTypeId", required = false) Long taskTypeId,
                     @RequestParam(value = "taskStatusId", required = false) Long taskStatusId,
                     @RequestParam(value = "createTime", required = false, defaultValue = "true") boolean createTime
    ) {
        String tzjb = null;
        UserResponse user = null;
        String xzqh = null;
        String level = null;
        try {
            user = userService.getOne(new QueryWrapper<UserResponse>().select("tzjb", "xzqdm").eq("id", userId));
            tzjb = user.getTzjb();
            xzqh = user.getXzqdm();
            level = districtService.getOne(new QueryWrapper<DistrictResponse>().select("level").eq("code",xzqh)).getLevel();
        } catch (Exception e) {
            return R.fail("未查询到该用户的田长级别");
        }
        IPage<TaskResponse> allTasks = null;
        //一级田长查看任务
        if ("1".equals(tzjb)) {
            allTasks = taskService.selectByAllWrapper(new Page<TaskResponse>(p, s), new QueryWrapper<TaskResponse>().
                    select("id", "task_name", "task_status_id", "cb", "task_s_time", "task_e_time").
                    like(StringUtils.isNotEmpty(taskName), "task_name", taskName).
                    eq(taskTypeId != 0, "task_type_id", taskTypeId).
                    eq(taskStatusId != 0, "task_status_id", taskStatusId).
                    orderByAsc(!createTime, "create_time").
                    orderByDesc(createTime, "create_time"));
            return R.success(allTasks);
        }
        //二级田长查看任务
        if ("2".equals(tzjb) || "2".equals(level)) {
            Long id = districtService.getOne(new QueryWrapper<DistrictResponse>().select("id").eq("code", xzqh)).getId();
            List<DistrictResponse> disList = districtService.list(new QueryWrapper<DistrictResponse>().select("code").eq("pid", id));
            List<String> xzqhList = new ArrayList<>();
            disList.stream().forEach(dis -> {
                xzqhList.add(dis.getCode());
            });
            allTasks = taskService.selectByAllWrapper(new Page<TaskResponse>(p, s), new QueryWrapper<TaskResponse>().
                    select("id", "task_name", "task_status_id", "cb", "task_s_time", "task_e_time").
                    like(StringUtils.isNotEmpty(taskName), "task_name", taskName).
                    eq(taskTypeId != 0, "task_type_id", taskTypeId).
                    eq(taskStatusId != 0, "task_status_id", taskStatusId).
                    ne("task_status_id","18").
                    in("xzqhdm", xzqhList).
                    orderByAsc(!createTime, "create_time").
                    orderByDesc(createTime, "create_time"));
            return R.success(allTasks);
        }
        //三级田长查看任务
        if ("3".equals(tzjb) || "4".equals(tzjb)) {
                allTasks = taskService.selectByAllWrapper(new Page<TaskResponse>(p, s), new QueryWrapper<TaskResponse>().
                        select("id", "task_name", "task_status_id", "cb", "task_s_time", "task_e_time").
                        like(StringUtils.isNotEmpty(taskName), "task_name", taskName).
                        eq(taskTypeId != 0, "task_type_id", taskTypeId).
                        eq(taskStatusId != 0, "task_status_id", taskStatusId).
                        eq("xzqhdm", xzqh).notIn("task_status_id", "18").
                        ne("task_status_id","18").
                        orderByAsc(!createTime, "create_time").
                        orderByDesc(createTime, "create_time"));
                return R.success(allTasks);
        }
        return R.success(null);
    }

    @ApiOperation(value = "历史任务批次列表", notes = "根据当前用户id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前用户的id", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskName", value = "根据批次名称查询", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "createTime", value = "创建时间排序(true倒序，false正序)", dataType = "boolean", paramType = "query", required = false)
    })
    @GetMapping("/historyTask")
    @AppToken
    public R<List<TaskResponse>> historyTask(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                                             @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                                             @RequestParam(value = "userId", required = false) String userId,
                                             @RequestParam(value = "taskName", required = false) String taskName,
                                             @RequestParam(value = "createTime", required = false, defaultValue = "true") boolean createTime) {
        String tzjb = null;
        UserResponse user = null;
        String xzqh = null;
        DistrictResponse districtResponse = null;
        String level = null;
        try {
            user = userService.getOne(new QueryWrapper<UserResponse>().select("tzjb", "xzqdm").eq("id", userId));
            tzjb = user.getTzjb();
            xzqh = user.getXzqdm();
            districtResponse = districtService.getOne(new QueryWrapper<DistrictResponse>().select("level","id").eq("code",xzqh));
            level=districtResponse.getLevel();
        } catch (Exception e) {
            return R.fail("未查询到该用户的田长级别");
        }
        IPage<TaskHistoryResponse> taskHistoryResponseIPage = null;
        //一级田长查看历史任务
        if ("1".equals(tzjb)) {
            taskHistoryResponseIPage = taskHistoryService.selectHistoryByProduction(new Page(p, s), new QueryWrapper<TaskHistoryResponse>().
                    like(StringUtils.isNotEmpty(taskName), "task_name", taskName).groupBy("production").
                    orderByAsc(!createTime, "create_time").orderByDesc(createTime, "create_time"));
            return R.success(taskHistoryResponseIPage);
        }
        //二级田长查看历史任务
        if ("2".equals(tzjb)||"2".equals(level)) {
            Long id = districtResponse.getId();
            List<DistrictResponse> disList = districtService.list(new QueryWrapper<DistrictResponse>().select("code").eq("pid", id));
            List<String> xzqhList = new ArrayList<>();
            disList.stream().forEach(dis -> {
                xzqhList.add(dis.getCode());
            });
            taskHistoryResponseIPage = taskHistoryService.selectHistoryByProduction(new Page(p, s), new QueryWrapper<TaskHistoryResponse>().
                    like(StringUtils.isNotEmpty(taskName), "task_name", taskName).in("xzqhdm", xzqhList).groupBy("production").
                    orderByAsc(!createTime, "create_time").orderByDesc(createTime, "create_time"));
            return R.success(taskHistoryResponseIPage);
        }
        //三级田长查看历史任务
        if ("3".equals(tzjb) || "4".equals(tzjb)) {
            taskHistoryResponseIPage = taskHistoryService.selectHistoryByProduction(new Page(p, s), new QueryWrapper<TaskHistoryResponse>().
                    like(StringUtils.isNotEmpty(taskName), "task_name", taskName).eq("xzqhdm", xzqh).groupBy("production").
                    orderByAsc(!createTime, "create_time").orderByDesc(createTime, "create_time"));
            return R.success(taskHistoryResponseIPage);
        }
        return R.success(null);
    }

    @ApiOperation(value = "历史任务批次详情", notes = "根据批次开始日期和行政区划号查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", paramType = "query"),
            @ApiImplicitParam(name = "production", value = "批次名称", dataType = "Date", paramType = "query", required = true),
            @ApiImplicitParam(name = "xzqhdm", value = "当前批次的行政区划号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "taskTypeId", value = "任务类型（15定期核查，16下发图斑，17上报事件）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "createTime", value = "创建时间排序(true倒序，false正序)", dataType = "boolean", paramType = "query", required = false)
    })
    @GetMapping("/historyTaskDetail")
    @AppToken
    public R historyTaskDetail(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                               @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                               @RequestParam(value = "production", required = false) String production,
                               @RequestParam(value = "xzqhdm", required = false) String xzqhdm,
                               @RequestParam(value = "taskTypeId", required = false) String taskTypeId,
                               @RequestParam(value = "createTime", required = false, defaultValue = "true") boolean createTime
    ) {
        Page<TaskHistoryResponse> historyResponsePage = taskHistoryService.page(new Page<TaskHistoryResponse>(p, s), new QueryWrapper<TaskHistoryResponse>().
                select("id","production","task_status_id","task_s_time","task_e_time","task_name").eq("xzqhdm", xzqhdm).
                eq("task_type_id", taskTypeId).eq("production", production).
                orderByDesc(createTime, "create_time").orderByAsc(!createTime, "create_time"));
        return R.success(historyResponsePage);
    }


    @ApiOperation(value = "开始任务", notes = "开始任务---json,实体类TaskRequest，参数id,taskXcr,xcrSX,xcrSY")
    @ApiImplicitParam(name = "taskRequest", value = "实体类TaskRequest", paramType = "body", required = true,dataType = "TaskRequest")
    @PostMapping("/startTask")
    @Transactional
    @AppToken
    public R startTask(@RequestBody TaskRequest taskRequest) {
        String tzjb = null;
        String taskId = null;
        String userId = null;
        BigDecimal scrSX = null;
        BigDecimal scrSY = null;
        try{
            userId = taskRequest.getTaskXcr().toString();
            tzjb = userService.getOne(new QueryWrapper<UserResponse>().select("tzjb").eq("id", userId)).getTzjb();
            taskId = taskRequest.getId().toString();
            scrSX = taskRequest.getXcrSX();
            scrSY = taskRequest.getXcrSY();
        }catch (Exception e){
            return R.fail("未查询到田长级别");
        }

        if ("1".equals(tzjb)) {
            return R.fail(ResultCode.ERROR.getCode(), "一级田长无法开始任务");
        }
        if ("2".equals(tzjb)) {
            return R.fail(ResultCode.ERROR.getCode(), "二级田长无法开始任务");
        }
        //当前人是否有巡查中任务
        //当前任务
        int isHasTask = taskService.count(new QueryWrapper<TaskResponse>().eq("task_xcr", userId).eq("task_status_id", 18));
        //历史任务表
        int isHasTaskHis = taskHistoryService.count(new QueryWrapper<TaskHistoryResponse>().eq("task_xcr", userId).eq("task_status_id", 18));
        if (isHasTask > 0 || isHasTaskHis > 0) {
            return R.fail(ResultCode.ERROR.getCode(), "巡查中任务只能开始一个");
        }
        String mes = "";
        //此任务是否开始过
        //当前任务
        TaskResponse isStart = taskService.getOne(new QueryWrapper<TaskResponse>().select("task_xcr").eq("id", taskId));
        //历史任务表
        TaskHistoryResponse isStartHis = taskHistoryService.getOne(new QueryWrapper<TaskHistoryResponse>().select("task_xcr").eq("id", taskId));
        if (isStart != null || isStartHis != null) {
            log.error("此任务已经有人开始");
            return R.fail(ResultCode.ERROR.getCode(), "此任务已经有人开始");
        } else {
            boolean res = taskService.update(new UpdateWrapper<TaskResponse>().set("task_status_id", 18).
                    set("task_xcr", userId).set("xcr_s_x", scrSX).set("xcr_s_y", scrSY).set("update_time", new Date()).
                    set("task_time", new Date()).eq("id", taskId));
            boolean resHis = taskHistoryService.update(new UpdateWrapper<TaskHistoryResponse>().set("task_status_id", 18).
                    set("task_xcr", userId).set("xcr_s_x", scrSX).set("xcr_s_y", scrSY).set("update_time", new Date()).
                    set("task_time", new Date()).eq("id", taskId));
            if (res || resHis) {
                mes = "开始成功";
                //任务开始后新消息提醒减1
                UpdateWrapper<TzMes> update = new UpdateWrapper<TzMes>();
                update.set("state", "1");
                update.eq("id_by_type", taskRequest.getId()).in("type", "1", "4");
                mesService.update(update);
                return R.success(mes);
            } else {
                log.error("任务异常，请联系后台管理人员");
                return R.fail(ResultCode.ERROR.getCode(), "任务异常，请联系后台管理人员");
            }
        }
    }

    @ApiOperation(value = "结束任务", notes = "结束任务")
    @ApiImplicitParam(name = "eTRequest", value = "实体类ETRequest",paramType = "body", required = true,dataType = "TaskRequest")
    @PostMapping("/endTask")
    @Transactional
    @AppToken
    public R endTask(@Valid @RequestBody ETRequest eTRequest) {
        PatrolResponse patrolResponse = eTRequest.getPatrolRequest();
        List<TrajectoryRequest> trajectoryRequestList = eTRequest.getTrajectoryRequest();
        List<PatrolFileResponse> patrolFileResponseList = eTRequest.getPics();
        String tzjb = null;
        try {
            tzjb = userService.getOne(new QueryWrapper<UserResponse>().select("tzjb").eq("id", patrolResponse.getUserId().toString())).getTzjb();
        } catch (NullPointerException e) {
            return R.fail(ResultCode.ERROR.getCode(), "未找到该用户id");
        }
        if ("1".equals(tzjb)) {
            return R.fail(ResultCode.ERROR.getCode(), "一级田长无法完成任务");
        }
        if ("2".equals(tzjb)) {
            return R.fail(ResultCode.ERROR.getCode(), "二级田长无法完成任务");
        }
        //任务状态更新
        try{
            taskService.update(new UpdateWrapper<TaskResponse>().set("task_status_id", "20").set("update_time", new Date())
                    .eq("id", patrolResponse.getTaskId()));
            taskHistoryService.update(new UpdateWrapper<TaskHistoryResponse>().set("task_status_id", "20").set("update_time", new Date())
                    .eq("id", patrolResponse.getTaskId()));
        }catch (Exception e){
            return R.fail("任务状态更新失败");
        }
        boolean resPatrol = false;
        try{
            String xcsj = dateDiff(patrolResponse.getSTime().getTime(), System.currentTimeMillis());
            patrolResponse.setXcsj(xcsj);
            Calendar c = Calendar.getInstance();
            c.setTime(patrolResponse.getETime());
            String year = String.valueOf(c.get(Calendar.YEAR));
            patrolResponse.setXcnf(year);
            int m = c.get(Calendar.MONTH) + 1;
            String month = String.valueOf(m);
            patrolResponse.setXcyf(month);
            patrolResponse.setXczt("1");
            patrolResponse.setCreateTime(new Date());
            patrolResponse.setUpdateTime(new Date());
            resPatrol = patrolService.save(patrolResponse);
        }catch (Exception e){
            return R.fail("巡查信息更新失败");
        }
        if(resPatrol){
            MessageVo messageVo = new MessageVo();
            messageVo.setTaskId(patrolResponse.getTaskId());
            messageVo.setUserId(patrolResponse.getUserId());
            String mes = JSONObject.toJSONString(messageVo);
            sender.sendMsg(mes);
        }
        //轨迹记录，多条数据
        if (trajectoryRequestList != null && trajectoryRequestList.size() > 0) {
            for(TrajectoryRequest s:trajectoryRequestList){
                s.setCreateTime(new Date());
                s.setUpdateTime(new Date());
            }
            trajectoryService.saveBatch(trajectoryRequestList);
        }
        //任务异常上传图片
        if (patrolFileResponseList != null && patrolFileResponseList.size() > 0) {
            patrolFileService.saveBatch(patrolFileResponseList);
        }
        return R.success("任务结束");
    }

    @ApiOperation(value = "地图图斑", notes = "返回图斑id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "Long", required = true),
            @ApiImplicitParam(name = "taskStatusId", value = "图斑巡查状态", paramType = "String", required = true)
    }
    )
    @GetMapping("/tbId")
    @AppToken
    public R taskTbId(@RequestParam(value = "s", required = false, defaultValue = "20") Long s,
                                    @RequestParam(value = "p", required = false, defaultValue = "1") Long p,
                                    @RequestParam(value = "userId",required = false) Long userId,
                                    @RequestParam(value = "taskStatusId",required = false) String taskStatusId) {
        String tzjb = null;
        String xzqdm = null;
        String level = null;
        try {
            UserResponse user = userService.getOne(new QueryWrapper<UserResponse>().select("tzjb", "xzqdm").eq("id", userId));
            tzjb = user.getTzjb();
            xzqdm = user.getXzqdm();
            List<String> tbList = new ArrayList<>();
            level = districtService.getOne(new QueryWrapper<DistrictResponse>().select("level").eq("code",xzqdm)).getLevel();
        } catch (Exception e) {
            return R.fail("未查询到行政区划级别");
        }
        if(tzjb.equals("1")){
            Page<TaskResponse> taskList = taskService.page(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().select("tb_id").eq("task_status_id",taskStatusId));
            return R.success(taskList);
        }
        if(TZJB_2.equals(tzjb)||TZJB_2.equals(level)){
            Long id = districtService.getOne(new QueryWrapper<DistrictResponse>().select("id").eq("code", xzqdm)).getId();
            List<DistrictResponse> disList = districtService.list(new QueryWrapper<DistrictResponse>().select("code").eq("pid", id));
            List<String> xzqhList = new ArrayList<>();
            disList.stream().forEach(dis -> {
                xzqhList.add(dis.getCode());
            });
            Page<TaskResponse> taskList = taskService.page(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().select("tb_id").in("xzqhdm",xzqhList).
                    eq("task_status_id",taskStatusId));
            return R.success(taskList);
        }else if(tzjb.equals("3")||tzjb.equals("4")){
            Page<TaskResponse> taskList = taskService.page(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().select("tb_id").eq("xzqhdm",xzqdm).
                    eq("task_status_id",taskStatusId));
            return R.success(taskList);
        }else {
            return R.success(null);
        }
    }

    @ApiOperation(value = "历史任务任务详情", notes = "历史任务任务详情")
    @ApiImplicitParam(name = "id", value = "任务主键id", dataType = "Long", paramType = "query", required = true)
    @GetMapping("/taskDetail")
    @AppToken
    public R<TPPResponse> taskDetail(Long id) {
        TPPResponse tppResponse = new TPPResponse();
        PatrolResponse patrolResponse = patrolService.getOne(new QueryWrapper<PatrolResponse>().select("s_time", "e_time",
                "xcsj", "xclc", "xczt", "task_describe", "task_status").eq("task_id", id));
        List<PatrolFileResponse> PFileList = patrolFileService.list(new QueryWrapper<PatrolFileResponse>().select("file_path").
                eq("task_id", id));
        List<String> pics = new ArrayList<>();
        for (PatrolFileResponse p : PFileList) {
            pics.add(p.getFilePath());
        }
        tppResponse.setPatrol(patrolResponse);
        tppResponse.setPics(pics);
        TaskResponse taskResponse = taskService.hisTaskDetail(id);
        tppResponse.setTask(taskResponse);
        return R.success(tppResponse);
    }

    @ApiOperation(value = "田长信息", notes = "图斑信息中田长信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "xzqdm", value = "行政区划", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/selectTz")
    @AppToken
    public R<List<UserResponse>> selectTz(String xzqdm) {
        List<UserResponse> users = userService.selectTZ(new QueryWrapper<UserResponse>().eq("xzqdm",xzqdm));
        return R.success(users);
    }

    @ApiOperation(value = "二级田长催办任务",notes = "二级田长催办任务")
    @ApiImplicitParam(name = "id",value = "任务id",dataType = "Long",paramType = "query",required = true)
    @GetMapping("/cbTasks")
    @AppToken
    @Transactional
    public R cbTasks(Long id){
        if(id==null || id==0){
            return R.fail(ResultCode.ERROR.getCode(),"id不能为空");
        }
        boolean taskNow = taskService.update(new UpdateWrapper<TaskResponse>()
                .lambda()
                .set(TaskResponse::getCb,CB_1)
                .set(TaskResponse::getUpdateTime,new Date())
                .eq(id!=null&id.longValue()!=0,TaskResponse::getId,id));
        boolean taskHis = taskHistoryService.update(new UpdateWrapper<TaskHistoryResponse>().set("cb",CB_1).eq("id",id));
        if (taskNow || taskHis){
            Long user =  null;
            try {
                user = taskService.getOne(new QueryWrapper<TaskResponse>().select("task_xcr").eq("id",id)).getTaskXcr();
            } catch (Exception e) {
                System.out.println("任务没有巡查人");
                log.error("任务没有巡查人");
            }
            if(user!=null){
                try {
                    TzMes tzMes = new TzMes();
                    tzMes.setMessage("收到一条催办任务");
                    tzMes.setIdByType(id);
                    tzMes.setType("4");
                    tzMes.setRoutingKey("transaction_tz");
                    tzMes.setUserId(user);
                    sender.sendOtherMes(JSONObject.toJSONString(tzMes));
                }catch (Exception e){
                    System.out.println("消息推送失败");
                    log.error("消息推送失败");
                }
            }
            return R.success("催办成功");
        }else {
            return R.fail(ResultCode.ERROR.getCode(),"催办失败，请重试");
        }
    }
    @ApiOperation(value = "统计列表",notes = "二级田长登入统计列表查看")
    @ApiImplicitParam(name = "id",value = "用户id",dataType = "Long",paramType = "query",required = true)
    @GetMapping("/statisticsList")
    @AppToken
    public R<CountComResponse> statisticsList(Long id){
        /*获取二级田长相关信息*/
        UserResponse user = userService.getById(id);
        /*获取二级田长的行政区代码信息*/
        DistrictResponse dis = districtService.getOne(new QueryWrapper<DistrictResponse>()
                .lambda()
                .eq(DistrictResponse::getCode,user.getXzqdm()));
        /*检索子级区划码*/
        List<String> codeList = districtService.list(new QueryWrapper<DistrictResponse>()
                .lambda().eq(DistrictResponse::getPid,dis.getId()))
                .stream().map(DistrictResponse::getCode).collect(Collectors.toList());
        /*面积*/
        Double mj = taskService.sumMj(new QueryWrapper<TaskResponse>()
                .eq("task_type_id",15L)
                .in("xzqhdm",codeList));
        /*根据行政区代码检索所有任务，任务表/历史任务表*/
        List<TaskResponse> allTasks = taskService.allTasks(new QueryWrapper<TaskResponse>()
                .in("t.xzqhdm",codeList));
        /*根据行政区划获取所有子级田长的id*/
        List<Long> userId = userService.list(new QueryWrapper<UserResponse>()
                        .lambda()
                        .select(UserResponse::getId)
                        .in(UserResponse::getXzqdm,codeList))
                .stream().map(UserResponse::getId).collect(Collectors.toList());
        /*根据用户id检索所有子级田长上报的事件 同时是上报事件的数量*/
        List<Long> finalUserId = userId;
        List<EventResponse> eventList = eventService.list(new QueryWrapper<EventResponse>()
                .lambda()
                .gt(EventResponse::getTaskId,0)
                .and(wrapper->wrapper.in(EventResponse::getHandler, finalUserId).or().in(EventResponse::getReportBy, finalUserId)));
        /*已巡查任务*/
        List<TaskResponse> yxc = allTasks.stream().filter(item -> item.getTaskStatusId().equals(20L)).collect(Collectors.toList());
        /*巡查中任务*/
        List<TaskResponse> xcz = allTasks.stream().filter(item -> item.getTaskStatusId().equals(18L)).collect(Collectors.toList());
        /*已解决事件*/
        List<EventResponse> yjj = eventList.stream().filter(item -> item.getEventStatusId().equals(12L)).collect(Collectors.toList());
        /*待解决事件*/
        List<EventResponse> djj = eventList.stream().filter(item -> item.getEventStatusId().equals(11L)).collect(Collectors.toList());
        /*进行中的事件 包括待审核和待解决*/
        List<EventResponse> jxz = eventList.stream().filter(item -> item.getEventStatusId().equals(10L)||item.getEventStatusId().equals(11L)).collect(Collectors.toList());
        /*已逾期任务*/
        List<TaskResponse> yyq = allTasks.stream().filter(item -> item.getTaskStatusId().equals(21L)).collect(Collectors.toList());
        /*返回数量*/
        CountResponse countResponse = new CountResponse();
        countResponse.setArableLand(Double.parseDouble(new DecimalFormat("#.0000").format(mj/666.67)));
        countResponse.setPermanentLand(Double.parseDouble(new DecimalFormat("#.0000").format(mj/666.67)));
        countResponse.setInspected(yxc.size());
        countResponse.setInspecting(xcz.size());
        countResponse.setSolved(yjj.size());
        countResponse.setToSolved(djj.size());
        countResponse.setOutTime(yyq.size());
        /*乡镇任务*/
        List<CompletionResponse> cr0 = new ArrayList<>();
        CompletionResponse cr1 = new CompletionResponse();
        cr1.setName(dis.getName());
        cr1.setTaskCompleted(yxc.size());
        cr1.setTaskCompleting(xcz.size());
        cr1.setTaskTimeOut(yyq.size());
        cr1.setAllTasks(allTasks.size());
        cr1.setTaskCompletion((allTasks.size()!=0&&yxc.size()!=0)?new DecimalFormat("#.00").format((double) yxc.size()/allTasks.size()*100):"0");
        cr1.setReported(eventList.size());
        cr1.setEventCompleting(jxz.size());
        cr1.setEventCompleted(yjj.size());
        cr1.setAllEvents(eventList.size());
        cr1.setEventCompletion((eventList.size()!=0&&yjj.size()!=0)?new DecimalFormat("#.00").format((double) yjj.size()/eventList.size()*100):"0");
        cr0.add(cr1);
        /*村任务*/
        List<CompletionResponse> cr = taskService.allChild(new QueryWrapper<DistrictResponse>().lambda().in(DistrictResponse::getCode,codeList));
        for (CompletionResponse completionResponse : cr) {
            System.out.println(completionResponse);
        }
        Map<String,Object> map = new HashMap<>(3);
        map.put("count",countResponse);
        map.put("Completion1",cr0);
        map.put("Completion2",cr);
        return R.success(map);
    }
    @ApiOperation(value = "查询巡查中的任务开始时长",notes = "查询巡查中的任务开始时长")
    @GetMapping("/oneHourEndTask")
    @AppToken
    public R oneHourEndTask(String userId){
        int hasTask = taskService.count(new QueryWrapper<TaskResponse>().eq("task_xcr",userId).eq("task_status_id","18"));
        if(hasTask>0){
            Map map = new HashMap();
            TaskResponse task = taskService.getOne(new QueryWrapper<TaskResponse>().select("id","task_time").
                    eq("task_xcr",userId).eq("task_status_id","18"));
            map.put("id",task.getId());
            map.put("task_time",task.getTaskTime());
            Long time =  (System.currentTimeMillis()-task.getTaskTime().getTime())/1000/60;
            map.put("time",time);
            return R.success(map);
        }else {
            return R.success(null);
        }
    }
}
